
package com.hulk.dryad.manage.provider.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hulk.dryad.common.constant.enums.DelFlag;
import com.hulk.dryad.common.util.SpringContextHolder;
import com.hulk.dryad.manage.provider.service.GenDatasourceConfService;
import com.hulk.dryad.persistence.entity.GenDatasourceConfModel;
import com.hulk.dryad.persistence.entity.SysDeptModel;
import com.hulk.dryad.persistence.entity.enums.DsConfTypeEnum;
import com.hulk.dryad.persistence.entity.enums.DsJdbcUrlEnum;
import com.hulk.dryad.persistence.mapper.GenDatasourceConfMapper;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据源表
 *
 * @author kim
 * @date 2019-03-31 16:00:20
 */
@Slf4j
@Service
@AllArgsConstructor
public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfMapper, GenDatasourceConfModel>
		implements GenDatasourceConfService {


	private final StringEncryptor stringEncryptor;

	private final DataSourceCreator dataSourceCreator;

	private final boolean pwdEncryptEnable = false;

	/**
	 * 保存数据源并且加密
	 * @param conf
	 * @return
	 */
	@Override
	public Boolean saveDsByEnc(GenDatasourceConfModel conf) {
		// 数据源名称校验
		LambdaQueryWrapper<GenDatasourceConfModel> qw = Wrappers.<GenDatasourceConfModel>lambdaQuery()
				.eq(GenDatasourceConfModel::getName, conf.getName()).eq(GenDatasourceConfModel::getDelFlag, DelFlag.N.getValue());
		if (this.count(qw) > 0) {
			return Boolean.FALSE;
		}
		// 校验配置合法性
		if (!checkDataSource(conf)) {
			return Boolean.FALSE;
		}

		// 添加动态数据源
		addDynamicDataSource(conf);

		// 更新数据库配置
		if (pwdEncryptEnable) {
			conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
		} else {
			conf.setPassword(conf.getPassword());
		}
		this.baseMapper.insert(conf);
		return Boolean.TRUE;
	}

	/**
	 * 更新数据源
	 * @param conf 数据源信息
	 * @return
	 */
	@Override
	public Boolean updateDsByEnc(GenDatasourceConfModel conf) {
		// 数据源名称校验
		LambdaQueryWrapper<GenDatasourceConfModel> qw = Wrappers.<GenDatasourceConfModel>lambdaQuery()
				.eq(GenDatasourceConfModel::getName, conf.getName()).eq(GenDatasourceConfModel::getDelFlag, DelFlag.N.getValue());
		if (this.count(qw) > 0) {
			return Boolean.FALSE;
		}
		if (!checkDataSource(conf)) {
			return Boolean.FALSE;
		}
		// 先移除
		DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
		dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName());

		// 再添加
		addDynamicDataSource(conf);

		// 更新数据库配置
		if (StrUtil.isNotBlank(conf.getPassword())) {
			if (pwdEncryptEnable) {
				conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
			} else {
				conf.setPassword(conf.getPassword());
			}
		}
		this.baseMapper.updateById(conf);
		return Boolean.TRUE;
	}

	/**
	 * 通过数据源名称删除
	 * @param dsId 数据源ID
	 * @return
	 */
	@Override
	public Boolean removeByDsId(Integer dsId) {
		DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
		dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(dsId).getName());
		this.baseMapper.deleteById(dsId);
		return Boolean.TRUE;
	}

	/**
	 * 添加动态数据源
	 * @param conf 数据源信息
	 */
	@Override
	public void addDynamicDataSource(GenDatasourceConfModel conf) {
		DataSourceProperty dataSourceProperty = new DataSourceProperty();
		dataSourceProperty.setPoolName(conf.getName());
		dataSourceProperty.setUrl(conf.getUrl());
		dataSourceProperty.setUsername(conf.getUsername());
		if (pwdEncryptEnable) {
			dataSourceProperty.setPassword(stringEncryptor.decrypt(conf.getPassword()));
		} else {
			dataSourceProperty.setPassword(conf.getPassword());
		}
		DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);

		DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
		dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
	}

	/**
	 * 校验数据源配置是否有效
	 * @param conf 数据源信息
	 * @return 有效/无效
	 */
	@Override
	public Boolean checkDataSource(GenDatasourceConfModel conf) {
		String url;
		// JDBC 配置形式
		if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) {
			url = conf.getUrl();
		}
		else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
			// 主机形式 sql server 特殊处理
			DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
			url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getInstance(), conf.getPort(), conf.getDsName());
		}
		else {
			DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
			url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
		}

		conf.setUrl(url);

		try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) {
		}
		catch (SQLException e) {
			log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}

}
